<!-- 上传组件封装 -->
<template>
	<div>
		<el-upload class="upload-demo" ref="my-upload" :action="$use.linkUrl('/api/index/uploadImage')"
			:on-success="handleImageSuccess" :http-request="uploadRequest" :on-remove="handleRemove" :limit="limit"
			:list-type="listType" :file-list="fileList" :on-exceed="exceed" :headers="{Authorization:userInfo.token}"
			:on-preview="handlePictureCardPreview">
			<slot name="icon" v-if="isIcon"></slot>
			<i class="el-icon-plus "  v-else></i>
			
			
			
		</el-upload>
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	export default {
		name: "baseUpload",
		// listType :text,picture  文件列表的类型
		// isIcon：是否显示自定义插槽图片
		props: {

			value: {
				type: [String,Array],
				default:''
				// default:()=>[]
				
			},
			listType: {
				type: String,
				default: 'picture-card'
			},
			isIcon: {
				type: Boolean,
				default: false
			},

			limit: {
				type: [String, Number],
				default: 3
			},
			arrayType:{
				type: String,
				default: 'String'
			}

		},
		computed: {
			...mapState(['userInfo']),
		},

		data() {
			return {
				fileList: [],
				tempImg: [],
				dialogImageUrl: '',
				dialogVisible: false,
				imageListString: ''
			}
		},
		methods: {
			clearFiles() {
				this.$refs['my-upload'].clearFiles();
			},
			watchValue() {
				// 回显数组是数据还是字符串
				if(this.arrayType=="String"){
					var valueArray = this.value ? this.value.split(',') : [];
				}else{
					var valueArray = this.value;
				}
				this.fileList = valueArray.map(item => {
					return {
						name: item,
						url: this.$use.linkUrl(item),
					};
					
				});
				
			},
			uploadRequest(f) {
				let param = new FormData(); //创建form对象
				param.append(this.name, f.file); //通过append向form对象添加数据
				this.axios.post( this.listType=="picture-card"?"/index/uploadImage":"/index/uploadFile", param)
					.then(res => {
						f.onSuccess({
							url: res[0].host + res[0].src
						});
					})
					.catch(() => {
						f.onError();
					});
			},
			handleImageSuccess(res, file, fileList) {
				// 回显数组是数据还是字符串
				if(this.arrayType=="String"){
					this.emitInput(this.value ? this.value + ',' + res.url : res.url);
				}else{
					this.value.push(res.url)
					this.emitInput(this.value)
				}
			},
			emitInput(value) {
				this.$emit('input', value);
			},
			handleRemove(file, fileList) {
			   const fileArray = fileList.map(item => {
					return item;
				});
				this.emitInput(fileArray);
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			exceed(e) {
				this.$message.error('最多只能上传' + this.limit + '张')
			},


		}
	}
</script>

<style>

</style>
